package com.itcast.tcp.client.handler;

import com.itcast.tcp.protocol.MyProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-23 10:54
 **/
public class ClientTcpPackageHandler extends SimpleChannelInboundHandler<MyProtocol> {
    
    private int count = 0;
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; i++) {
            byte[] bytes = "from client a message! ".getBytes();
            MyProtocol myProtocol = new MyProtocol();
            myProtocol.setLength(bytes.length);
            myProtocol.setBytes(bytes);
            ctx.writeAndFlush(myProtocol);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        
        cause.printStackTrace();
        ctx.close();
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                MyProtocol myProtocol) throws Exception {
        System.out.println("服务器响应的消息为: " +
                new String(myProtocol.getBytes(), CharsetUtil.UTF_8));
        System.out.println("消息数量为: " + (++count));
    }
}
